package com.uduemc.biso.node.web.component.operate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModel;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModelAction;
import com.uduemc.biso.node.core.operate.entities.OperateLog;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.dto.RequestSCategory;
import com.uduemc.biso.node.web.api.service.SystemService;

@Aspect
@Component
public class OperateLoggerCategoryController extends OperateLoggerController {

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.CategoryController.save(..))", returning = "returnValue")
	public void save(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		Signature signature = point.getSignature();
		String declaringTypeName = signature.getDeclaringTypeName();
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = "";

		// 参数1
		String paramString = objectMapper.writeValueAsString(args[0]);
		RequestSCategory requestSCategory = objectMapper.readValue(paramString, RequestSCategory.class);
		Long id = requestSCategory.getId();
		Long systemId = requestSCategory.getSystemId();
		SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
		SSystem sSystem = systemServiceImpl.getInfoById(systemId);

		String content = null;
		if (id != null && id > 0) {
			modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
					OperateLoggerStaticModelAction.UPDATE);
			content = "编辑系统分类（系统：" + sSystem.getName() + " 分类：" + requestSCategory.getName() + "）";
		} else {
			modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
					OperateLoggerStaticModelAction.INSERT);
			content = "新建系统分类（系统：" + sSystem.getName() + " 分类：" + requestSCategory.getName() + "）";
		}

		String returnValueString = objectMapper.writeValueAsString(returnValue);
		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.CategoryController.delete(..))", returning = "returnValue")
	public void delete(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		Signature signature = point.getSignature();
		String declaringTypeName = signature.getDeclaringTypeName();
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.DELETE);

		// 参数1
		String paramString = objectMapper.writeValueAsString(args[0]);
		Long id = Long.valueOf(paramString);

		JsonResult jsonResult = (JsonResult) returnValue;
		@SuppressWarnings("unchecked")
		List<SCategories> listSCategories = (List<SCategories>) jsonResult.getData();

		SCategories sCategories = null;
		for (SCategories item : listSCategories) {
			if (item.getId().longValue() == id.longValue()) {
				sCategories = item;
			}
		}
		if (sCategories == null) {
			throw new RuntimeException(
					"通过传递的参数id以及返回的结果的数据当中未能找到对应的id的数据！id: " + id + " listSCategories: " + listSCategories);
		}

		Long systemId = sCategories.getSystemId();
		SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
		SSystem sSystem = systemServiceImpl.getInfoById(systemId);

		String content = "删除系统分类";
		content += "（ 系统：" + sSystem.getName() + " 分类：";
		content += sCategories.getName();
		if (listSCategories.size() > 1) {
			content += " 及其子级";
			int i = 0;
			for (SCategories item : listSCategories) {
				if (item.getId().longValue() == id.longValue()) {
					continue;
				}
				if (0 == i++) {
					content += item.getName();
				} else {
					content += "、" + item.getName();
				}
			}
		}
		content += "）";
		String returnValueString = objectMapper.writeValueAsString(returnValue);
		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.CategoryController.updateOrder(..))", returning = "returnValue")
	public void updateOrder(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		Signature signature = point.getSignature();
		String declaringTypeName = signature.getDeclaringTypeName();
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.UPDATE_ORDER);

		// 参数1
		String paramString0 = objectMapper.writeValueAsString(args[0]);
		List<SCategories> listSCategories = objectMapper.readValue(paramString0,
				new TypeReference<ArrayList<SCategories>>() {
				});
		// 参数2
		String paramString1 = objectMapper.writeValueAsString(args[1]);
		Long categoryId = objectMapper.readValue(paramString1, Long.class);

		List<Object> param = new ArrayList<>();
		param.add(listSCategories);
		param.add(categoryId);
		String paramString = objectMapper.writeValueAsString(param);

		SCategories sCategories = null;
		for (SCategories item : listSCategories) {
			if (item.getId().longValue() == categoryId.longValue()) {
				sCategories = item;
			}
		}

		Long systemId = sCategories.getSystemId();
		SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
		SSystem sSystem = systemServiceImpl.getInfoById(systemId);

		String content = "修改系统分类排序";
		if (sCategories != null) {
			content += "（系统：" + sSystem.getName() + " 分类：" + sCategories.getName() + "）";
		}

		String returnValueString = objectMapper.writeValueAsString(returnValue);
		OperateLog log = makeOperateLog(modelName, modelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}

}
